<style lang="less" scoped>
@import "../../../assets/css/applyList.less";
</style>
<template>
    <div class="listRecord search applyList">
        <Form ref="searchForm" :model="searchForm" inline :label-width="140" class="search-form rui-query-form">
            <div class="applyQuerySearchRow">
                <div class="applyQueryHead"></div>
                <div class="applyQuerySearchItem">
                    <Form-item label="" prop="socUniCrtCode">
                        <div>
                            <Input prefix="ios-search" type="text" v-model="searchForm.corporateName" @keyup.enter.native="handleSearch" clearable placeholder="法人名称"
                            />
                            <a :style="{display:'block',width:'40px',lineHeight: '24px',marginLeft: '16px'}"  @click="dropDown">
                                {{dropDownContent}}
                                <Icon :type="dropDownIcon"></Icon>
                            </a>
                        </div>
                    </Form-item>
                </div>
            </div>
            <div v-if="drop" class="applyQuerySearchMore table-card">
                <div  class="applyQuerySearchMoreRow">
                    <div class="rui-query-form-item">
                        <Form-item label="车商名称" prop="cardealerName"  >
                            <Select v-model="searchForm.cardealerName" clearable filterable placeholder="请选择">
                                <Option v-for="(item) in cardealerNameData" :value="item" :label="item"  :key="item.index"></Option>
                            </Select>
                        </Form-item>
                    </div>
                    <div class="rui-query-form-item">
                        <Form-item label="业务员" prop="salesMan" >
                            <Select v-model="searchForm.salesMan" clearable placeholder="请选择"  filterable>
                                <Option v-for="(item,k1) in userData" :value="item.username" :label="item.userRealName"  :key="k1"></Option>
                            </Select>
                        </Form-item>
                    </div>
                    <div class="rui-query-form-item">
                        <Form-item label="状态" prop="status" >
                            <Select v-model="searchForm.status" placeholder="请选择" clearable >
                                <Option value="00">启用</Option>
                                <Option value="01">审核中</Option>
                                <Option value="02">草稿</Option>
                                <Option value="03">退回</Option>
                                <Option value="04">拒绝</Option>
                                <Option value="05">停用</Option>
                            </Select>
                        </Form-item>
                    </div>
                </div>
                <div style="text-align: center">
                    <Button @click="handleSearch" type="primary">查询</Button>
                    &nbsp;&nbsp;&nbsp;&nbsp;
                    <Button @click="handleReset">重置</Button>
                </div>
            </div>
        </Form>
        <div class="table-card">
            <div class="btn-status flex flex-between">
                <div class="loanApplyBtn">
                    <Button @click="addCommonDealer" class="btn" size="default">新增普通车商</Button>
                    <Button @click="editSalesman" class="btn" size="default" >业务员批量修改</Button>
                    <Button @click="disable" class="btn" type="error" size="default">批量停用</Button>
                </div>
            </div>
            <div class="rui-table-box">
                <Table :loading="loading" :columns="columns" :data="data" sortable="custom"
                       @on-sort-change="changeSort" @on-selection-change="showSelect" ref="selection">

                    <template slot-scope="{ row, index }" slot="cardealerName" >
                        <a style="color: blue;" @click="checkCarDealer(row)">{{row.cardealerName}}</a>
                    </template>

                    <template slot-scope="{ row, index }" slot="cooperationMode" >
                        <span>{{row.cooperationMode=="0"?"本地合作":"异地合作"}}</span>
                    </template>

                    <template slot-scope="{ row, index }" slot="location">
                        <span>{{getDetailAddress1(row.locationProvince,row.locationCity)}}</span>
                    </template>

                    <template slot-scope="{ row, index }" slot="address">
                        <span>{{getDetailAddress2(row.channelProvince,row.channelCity,row.address)}}</span>
                    </template>
                    <template slot-scope="{ row, index }" slot="cardealerProperties" >
                        <span>{{row.cardealerProperties=="0"?"汽贸":""}}</span>
                        <span>{{row.cardealerProperties=="1"?"4S":""}}</span>
                        <span>{{row.cardealerProperties=="2"?"其他":""}}</span>
                    </template>
                    <template slot-scope="{ row,  }" slot="status">
                        <Badge v-if="row.coopeStatus==='00'" text="启用" color="#67c23a"/>
                        <Badge v-if="row.coopeStatus==='01'" text="审核中" color="#999"/>
                        <Badge v-if="row.coopeStatus==='02'" text="草稿" color="#999"/>
                        <Badge v-if="row.coopeStatus==='03'" text="退回" color="#e6a23c"/>
                        <Badge v-if="row.coopeStatus==='04'" text="拒绝" color="#e6a23c"/>
                        <Badge v-if="row.coopeStatus==='05'" text="停用" color="#f56c6c"/>

<!--                        <div v-if="row.coopeStatus == '00'">-->
<!--                            <Tag color="success" size="default">启用</Tag>-->
<!--                        </div>-->
<!--                        <div v-if="row.coopeStatus == '01'">-->
<!--                            <Tag color="warning" size="default">审核中</Tag>-->
<!--                        </div>-->
<!--                        <div v-if="row.coopeStatus == '02'">-->
<!--                            <Tag color="default" size="default">草稿</Tag>-->
<!--                        </div>-->
<!--                        <div v-if="row.coopeStatus == '03'">-->
<!--                            <Tag color="warning" size="default">退回</Tag>-->
<!--                        </div>-->
<!--                        <div v-if="row.coopeStatus == '04'">-->
<!--                            <Tag color="error" size="default">拒绝</Tag>-->
<!--                        </div>-->
<!--                        <div v-if="row.coopeStatus == '05'">-->
<!--                            <Tag color="error" size="default">停用</Tag>-->
<!--                        </div>-->
                    </template>
                    <template slot-scope="{ row, index }" slot="salesMan" >
                        <span>{{getUserRealName(row.associAccount)}}</span>
                    </template>
                    <template slot-scope="{ row }" slot="action">
                                <span v-if="row.coopeStatus=='02'||row.coopeStatus=='05' || row.coopeStatus=='03'">
                                    <Button style="margin-right:5px" type="primary" size="small" @click="edit(row)">编辑</Button>
                                </span>
                        <span v-if="row.coopeStatus!='02'&&row.coopeStatus!='05' && row.coopeStatus!='03'">
                                    <Button disabled style="margin-right:5px" type="primary" size="small" @click="edit(row)">编辑</Button>
                                </span>
                        <span v-if="row.coopeStatus=='02'">
                                    <Button type="error" size="small" @click="remove(row)">删除</Button>
                                </span>
                        <span v-if="row.coopeStatus!='02'">
                                    <Button disabled type="error" size="small" @click="remove(row)">删除</Button>
                                </span>
                    </template>
                </Table>
            </div>
            <br/>
            <Row type="flex" justify="end">
                <Page :current="searchForm.pageNumber" :total="total" :page-size="searchForm.pageSize"
                      @on-change="changePage" @on-page-size-change="changePageSize" :page-size-opts="[10,20,50]"
                      size="small" show-total show-elevator show-sizer></Page>
            </Row>
        </div>
        <!--批量修改业务员-->
        <Modal title="请选择修改后的业务员" v-model="modal1" :mask-closable='false' :width="300" :styles="{top: '100px'}">
            <Select  placeholder="请选择" filterable v-model="editForm.salesMan" >
                <Option v-for="(item) in salesManData" :value="item.username" :label="item.userRealName"  :key="item.index"></Option>
            </Select>
            <div slot="footer" style="text-align:center;" >
                <Button type="text" @click="cancel">取消</Button>
                <Button type="primary" @click="ok">提交</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    import {
        getCarDealerData,
        bulkEditingSalesman,
        getAllSaleManByChannelId,
        disableCarDealerFromApply,
        bulkEditingSalesmanFromCase,
        disableCarDealerFromCase,
        getChannelInfoData,
        deleteCommonCardealerById,
        getChannelBaseInfo,
        getAllCardealerName,
    } from "@/projects/afs-apply/api/car-dealer/dealer";
    import circleLoading from "_c/circle-loading/circle-loading.vue";
    import {getLocation} from "_p/afs-apply/api/apply-report/personal/common";
    import {province, city, area} from "_p/afs-apply/assets/js/staticData.js";
    import {getChannelId } from "@/projects/afs-apply/api/register-mng/listRecord";


    export default {
        name: "carDealer-manage",
        components: {
            circleLoading
        },
        data() {
            const validateName = (rule, value, callback) => {
                var reg = /^[\u4e00-\u9fa5_a-zA-Z]+$/;
                if (!reg.test(value)) {
                    callback(new Error("输入格式有误!"));
                } else {
                    callback();
                }
            };
            return {
                modal1: false,

                loading: false,
                channels:[],
                operationLoading: false,
                drop: false,
                dropDownContent: "更多",
                dropDownIcon: "ios-arrow-down",
                selectCount: 0,
                selectList: [],
                deptId: [],
                selectDep: [],
                department: [],
                province:[],
                city:[],
                location:{
                    locationAddressinfo: [
                        {
                            detailAddress: []
                        }
                    ],
                },
                searchForm: {
                    channelId:"",
                    associAccount:"",
                    cardealerName: "",
                    corporateName: "",
                    channelFullName: "",
                    channelBelong: "",
                    salesMan:"",
                    pageNumber: 1,
                    pageSize: 10,
                    startDate: "",
                    endDate: "",
                    status:"",
                },
                editForm:{
                    salesMan:"",
                },
                status:"00",
                selectDate: null,
                userModalVisible: false,
                modalTitle: "",
                columns: [
                    {
                        type: "selection",
                        minWidth: 60,
                        maxWidth:60,
                        align: "center",
                        fixed: "left"
                    },
                    {
                        type: 'index',
                        title:"序号",
                        minWidth: 80,
                        align: "center",
                        fixed: "left"

                    },
                    {
                        title: "车商名称",
                        key: "cardealerName",
                        minWidth: 150,
                        slot: "cardealerName",
                        fixed: "left"
                    },

                    {
                        title: "所在区域",
                        slot: "location",
                        minWidth: 150,
                        align: "center",
                        //sortable: true
                    },
                    {
                        title: "法人姓名",
                        key: "corporateName",
                        minWidth: 120,
                        align: "center",
                    },
                    {
                        title: "手机号码",
                        key: "telephoneNumber",
                        minWidth: 115,
                        align: "center",
                    },
                    {
                        title: "合作模式",
                        slot: "cooperationMode",
                        minWidth: 130,
                        align: "center",
                    },

                    {
                        title: "车商性质",
                        slot: "cardealerProperties",
                        minWidth: 110,
                        //sortable: true
                        align: "center",

                    },
                    {
                        title: "主营品牌",
                        key: "mainBrand",
                        minWidth: 200,
                        ellipsis:true,
                        render: (h, params) => {
                            return h('div', [
                                h('span', {
                                    style: {
                                        display: 'inline-block',
                                        width: '100%',
                                        overflow: 'hidden',
                                        textOverflow: 'ellipsis',
                                        whiteSpace: 'nowrap'
                                    },
                                    domProps: {
                                        title: params.row.mainBrand
                                    }
                                }, params.row.mainBrand)
                            ])
                        }
                    },
                    {
                        title: "业务员",
                        key: "salesMan",
                        slot: "salesMan",
                        minWidth: 100,
                        align: "center",
                        //sortable: true,

                    },
                    {
                        title: "注册时间",
                        align: "center",
                        key: "registrationTime",
                        minWidth: 120,
                        //sortable: true,
                    },
                    {
                        title: "统一社会信用代码",
                        key: "socUniCrtCode",
                        minWidth: 200,
                        align: "center",
                        //align: "center",

                    },
                    {
                        title: "注册地址",
                        slot: "address",
                        minWidth: 250,
                        align: "center",
                        //sortable: true,

                    },
                    {
                        title: "状态",
                        slot: "status",
                        minWidth: 120,
                        align: "center",
                        //sortable: true,

                    },
                    {
                        title: "审批备注",
                        key: "approveRemark",
                        minWidth: 200,
                        ellipsis:true,
                        render: (h, params) => {
                            return h('div', [
                                h('span', {
                                    style: {
                                        display: 'inline-block',
                                        width: '100%',
                                        overflow: 'hidden',
                                        textOverflow: 'ellipsis',
                                        whiteSpace: 'nowrap'
                                    },
                                    domProps: {
                                        title: params.row.approveRemark
                                    }
                                }, params.row.approveRemark)
                            ])
                        }
                    },
                    {
                        title: "操作",
                        key: "action",
                        minWidth: 140,
                        align: "center",
                        fixed: "right",
                        slot: "action"
                    }
                ],
                data: [],
                cardealerNameData: [],
                total: 0,
                salesManData:[],
                userData:[],
                formValidate: {
                    /*corporateName: [
                        {validator: validateName, trigger: "blur"}
                    ],*/
                },
            };
        },
        methods: {
            init() {
                this.handleSearch();
                this.getProvinceData();
                this.getCityData();
               // this.getChannelId();
            },
            changePage(v) {
                this.searchForm.pageNumber = v;
                this.getCarDealerList();
              //  this.clearSelectAll();
            },
            changePageSize(v) {
                this.searchForm.pageSize = v;
                this.getCarDealerList();
            },



            getCarDealerList() {
                this.loading = true;
                getChannelId({}).then(res => {
                    if (res.code === "0000") {
                        this.searchForm.channelId = res.data;
                        // 获取合作商信息接口
                        getChannelBaseInfo(this.searchForm.channelId).then(res => {
                            if (res.code === "0000") {
                                this.searchForm.channelFullName = res.data[0].channelFullName;
                                let param ={
                                    cardealerName: this.searchForm.cardealerName,
                                    corporateName: this.searchForm.corporateName.replace(/\s*!/g,""),
                                    channelFullName: this.searchForm.channelFullName.replace(/\s*!/g,""),
                                    channelBelong: this.searchForm.channelBelong,
                                    associAccount:this.searchForm.salesMan,
                                    pageNumber: this.searchForm.pageNumber,
                                    pageSize: this.searchForm.pageSize,
                                    startDate: this.searchForm.startDate,
                                    endDate: this.searchForm.endDate,
                                    status:this.searchForm.status,
                                    channelId:this.searchForm.channelId,
                                }
                                getCarDealerData(param).then(res => {
                                    this.loading = false;
                                    if (res.code === "0000") {
                                        this.data = res.data.records;
                                        this.total = res.data.total;
                                        this.getUserData();
                                    }
                                });
                            }
                        });

                        getAllCardealerName({cardealerType:"01",channelId:this.searchForm.channelId}).then(res => {
                            if (res.code === "0000") {
                                this.cardealerNameData = res.data;
                            }
                        });

                        getAllSaleManByChannelId(this.searchForm.channelId,"01").then(res => {
                            if (res.code === "0000") {
                                this.salesManData=res.data;
                            }
                        });
                    }
                });

            },

            handleSearch() {
                this.searchForm.pageNumber = 1;
              //  this.searchForm.pageSize = 10;
                this.getCarDealerList();
            },

            handleReset() {
                this.$refs.searchForm.resetFields();
                this.selectDate = null;
                this.searchForm.startDate = "";
                this.searchForm.endDate = "";
                this.selectDep = [];
            },
            changeSort(e) {
                this.searchForm.sort = e.key;
                this.searchForm.order = e.order;
                if (e.order === "normal") {
                    this.searchForm.order = "";
                }
                this.getCarDealer();
            },

            addCommonDealer() {
                let params = {
                    type: '1'
                };
                this.afs.newTab(
                    this,
                    'projects/afs-apply/pages/car-dealer/common-car-dealer/commonDealerCheck',
                    '普通车商新增',
                    'ios-add',
                    params,
                    'common-cardealer-add',
                    [],
                    true);
                this.afs.newTab(this,'projects/afs-apply/pages/car-dealer/common-car-dealer/commonDealerCheck','普通车商新增','ios-add',params,'aa',[],true);
            },

            //停用车商
            disable() {
                if (this.selectCount <= 0) {
                    this.$Message.warning("您还未选择要停用的车商");
                    return;
                }
                let status = false;
                this.selectList.forEach(function (e) {
                    if(e.coopeStatus != '00'){
                        status = true;
                    }
                });
                if(status){
                    this.$Message.warning("只能停用已启用的车商");
                    return;
                }
                this.$Modal.confirm({
                    title: "确认停用",
                    content: "您确认要停用所选的 " + this.selectCount + " 条数据?",
                    onOk: () => {
                        let ids = [];
                        this.selectList.forEach(function (e) {
                            ids += e.id + ",";
                        });
                        ids = ids.substring(0, ids.length - 1);
                        this.operationLoading = true;
                        //禁用方法
                        disableCarDealerFromApply(ids,this.searchForm.channelId,"05").then(res => {
                            this.operationLoading = false;
                            if (res.code === "0000") {
                                this.$Message.success("停用成功");
                            }
                        });
                    }
                });
            },

            //批量修改业务员
            editSalesman() {
                if (this.selectCount <= 0) {
                    this.$Message.warning("您还未选择要修改的数据");
                    return;
                }
                this.editForm.salesMan="";
                let status = false;
                this.selectList.forEach(function (e) {
                    if(e.coopeStatus != '00' && e.coopeStatus != '05'){
                        status = true;
                    }
                });
                if(status){
                    this.$Message.warning("只能修改停用或已启用的车商的业务员");
                    return;
                }

                this.modal1=true;
                getAllSaleManByChannelId(this.searchForm.channelId,"01").then(res => {
                    if (res.code === "0000") {
                        this.salesManData=res.data;

                    }
                });
            },


            checkCarDealer(v) {
                let channel =[];
                getChannelInfoData(v.id).then(res => {
                    if (res.code === "0000") {
                        channel=res.data
                        let params = {
                            dealerId:v.id,
                            channelFullName:channel[0].channelFullName,
                            channelId:channel[0].channelId,
                            type: '0',
                        };
                        this.afs.newTab(
                            this,
                            'projects/afs-apply/pages/car-dealer/common-car-dealer/commonDealerCheck',
                            '普通车商'+v.cardealerName+"查看",
                            'ios-add',
                            params,
                            'common-cardealer-check'+v.id,
                            [],
                            true);
                    }else{
                        this.$Message.error("未知错误");
                    }
                });
            },

            edit(v) {
                let channel =[];
                getChannelInfoData(v.id).then(res => {
                    if (res.code === "0000") {
                        channel=res.data
                        let params = {
                            dealerId:v.id,
                            channelFullName:channel[0].channelFullName,
                            channelId:channel[0].channelId,
                            type: '2',
                        };
                        this.afs.newTab(
                            this,
                            'projects/afs-apply/pages/car-dealer/common-car-dealer/commonDealerCheck',
                            '普通车商'+v.cardealerName+"修改",
                            'ios-add',
                            params,
                            'common-cardealer-edit'+v.id,
                            [],
                            true);
                    }else{
                        this.$Message.error("未知错误");
                    }
                });
            },
            //根据车商id查询对应的渠道信息
            getChannelInfo(v){
              let id=v.id;
                getChannelInfoData(id).then(res => {
                    if (res.code === "0000") {
                        this.channels=res.data
                    }
                });
            },

            remove(v) {
                this.$Modal.confirm({
                    title: "确认删除",
                    content: "您确认要删除车商 " + v.cardealerName + " ?",
                    onOk: () => {
                        this.operationLoading = true;
                        deleteCommonCardealerById(v.id,this.searchForm.channelId).then(res => {
                            this.operationLoading = false;
                            if (res.code === "0000") {
                                this.$Message.success("删除成功");
                                this.handleSearch();
                            }
                        });
                    }
                });
            },
            dropDown() {
                if (this.drop) {
                    this.dropDownContent = "更多";
                    this.dropDownIcon = "ios-arrow-down";
                } else {
                    this.dropDownContent = "收起";
                    this.dropDownIcon = "ios-arrow-up";
                }
                this.drop = !this.drop;
            },
            showSelect(e) {
                this.selectList = e;
                this.selectCount = e.length;
            },

            ok(){
                let ids = [];
                let ids2 = [];
                this.selectList.forEach(function (e) {
                    ids += e.id + ",";
                    if(e.coopeStatus=="00"){
                        ids2 += e.id + ",";
                    }
                });
                ids = ids.substring(0, ids.length - 1);
                ids2 = ids2.substring(0, ids2.length - 1);
                //修改方法
                bulkEditingSalesman(this.editForm.salesMan,ids,this.searchForm.channelId).then(res => {
                    this.operationLoading = false;
                    if (res.code === "0000") {
                        bulkEditingSalesmanFromCase(this.editForm.salesMan,ids2,this.searchForm.channelId).then(res => {
                            if (res.code === "0000") {
                                this.$Message.success("修改成功");
                                this.handleSearch();
                            }
                        })
                    }
                });
                this.modal1=false;
            },
            cancel(){
                this.modal1=false;
            },

            //反向解析省市地址
            getProvinceData() {
                let param = {level:"1",upperCode: "1"};

                getLocation(param).then(res => {
                    if(res.code === "0000"){
                        this.province=res.data;
                    }
                });
            },
            getCityData() {
                let param = {level:2,upperCode:''};
                getLocation(param).then(res => {
                    if (res.code == "0000") {
                        this.city=res.data;
                    }
                });
            },

            getDetailAddress1(registeredProvince,registeredCity){
                if(registeredProvince!="" && registeredCity!=""){
                    let province="";
                    let city="";
                    for(let i=0;i<this.province.length;i++){
                        if(this.province[i].value==registeredProvince){
                            province=this.province[i].label;
                        }
                    };
                    for(let i=0;i<this.city.length;i++){
                        if(this.city[i].value==registeredCity){
                            city=this.city[i].label;
                        }
                    };
                        return province+city;
                }else{
                    return '';
                }
            },

            getDetailAddress2(registeredProvince,registeredCity,registeredAddress){
                if(registeredProvince!="" && registeredCity!="" && registeredAddress !=""){
                    let province="";
                    let city="";
                    for(let i=0;i<this.province.length;i++){
                        if(this.province[i].value==registeredProvince){
                            province=this.province[i].label;
                        }
                    };
                    for(let i=0;i<this.city.length;i++){
                        if(this.city[i].value==registeredCity){
                            city=this.city[i].label;
                        }
                    };
                        return province+city+registeredAddress;
                }else{
                    return '';
                }
            },

            getUserRealName(val){
                if(val==null ||val=="" ||val ==undefined){
                    return;
                }
                let dic = {};
                this.salesManData.forEach(column => {
                    if(column.username === val){
                        dic = column;
                    }
                });
                return dic.userRealName;
            },

            getUserData(){
                this.userData=[]
                var userSet = new Set();
                var userData = new Set();
                this.salesManData.forEach(column => {
                    userData.add(column);
                });
                this.data.forEach(item=>{
                    if(item.salesMan){
                        userSet.add(item.salesMan)
                    }
                })
                if(userSet){
                    userSet.forEach(item=>{
                        userData.forEach(column => {
                            if(column.username === item){
                                this.userData.push(column)
                            }
                        });
                    })
                }
            },

        },
        mounted() {
            this.init();
            var that = this;
        },
        watch: {
            '$route'(to,from){
                this.handleReset();
                this.handleSearch();
            }
        },
    };
</script>
